import java.*;
import java.awt.*;
import ij.*;
import ij.process.*;
import ij.gui.*;
import ij.plugin.*;
import org.python.util.PythonInterpreter; 
import org.python.core.*; 

public class Py4IJ_IDE implements PlugIn {

    public void run(String arg)
    {
        java.lang.String path = ij.IJ.getDirectory("plugins")+"Py4IJ/";
        java.lang.System.getProperties().setProperty("python.home", path);
        ij.IJ.showStatus("Initializing Jython Engine...");
        PythonInterpreter py = new PythonInterpreter();
        py.exec("import sys, os, ij");
        py.exec("plugpath=ij.IJ.getDirectory('plugins')");
        py.exec("sys.path.append(os.path.join(plugpath, 'Py4IJ'))");
        py.exec("sys.path.append(os.path.join(plugpath, 'Py4IJ', 'Py4IJ'))");
        py.exec("sys.path.append(os.path.join(plugpath, 'Py4IJ', 'site-packages'))");
        py.exec("from gui import Py4IJ; Py4IJ.Py4IJ()");
        ij.IJ.showStatus("Py4IJ IDE started");
    }

	public static String exec(String script)
    {
        java.lang.String path = ij.IJ.getDirectory("plugins")+"Py4IJ/";
        java.lang.System.getProperties().setProperty("python.home", path);
        ij.IJ.showStatus("Initializing Jython Engine...");
        PythonInterpreter py = new PythonInterpreter();
        py.exec("import sys, os, imp, ij");
        py.exec("plugpath=ij.IJ.getDirectory('plugins')");
        py.exec("sys.path.append(os.path.join(plugpath, 'Py4IJ'))");
        py.exec("sys.path.append(os.path.join(plugpath, 'Py4IJ', 'Py4IJ'))");
        py.exec("sys.path.append(os.path.join(plugpath, 'Py4IJ', 'site-packages'))");
        py.exec("class MyWrite:\n\tdef write(self, txt):\n\t\tij.IJ.log(txt)");
        py.exec("sys.stdout = MyWrite()");
        py.exec(script);
        return "";
	}
    
    public static String eval(String script)
    {
        java.lang.String path = ij.IJ.getDirectory("plugins")+"Py4IJ/";
        java.lang.System.getProperties().setProperty("python.home", path);
        ij.IJ.showStatus("Initializing Jython Engine...");
        PythonInterpreter py = new PythonInterpreter();
        py.exec("import sys, os, imp, ij");
        py.exec("plugpath=ij.IJ.getDirectory('plugins')");
        py.exec("sys.path.append(os.path.join(plugpath, 'Py4IJ'))");
        py.exec("sys.path.append(os.path.join(plugpath, 'Py4IJ', 'Py4IJ'))");
        py.exec("sys.path.append(os.path.join(plugpath, 'Py4IJ', 'site-packages'))");
        py.exec("class MyWrite:\n\tdef write(self, txt):\n\t\tij.IJ.log(txt)");
        py.exec("sys.stdout = MyWrite()");
        return py.eval(script).toString();
	}
}

